package com.ruoyi.web.controller.linepatrol;

import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.system.domain.RouteStation;
import com.ruoyi.system.domain.WaterMeterrepairinfo;
import com.ruoyi.system.service.IRouteStationService;
import com.ruoyi.web.controller.app.api.Result;
import com.ruoyi.web.controller.app.util.CoordinatesConvertUtil;
import com.ruoyi.web.controller.app.util.MapCordinatesVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PatrolRouteRecord;
import com.ruoyi.system.service.IPatrolRouteRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 巡线记录Controller
 *
 * @author ruoyi
 * @date 2025-10-17
 */
@RestController
@RequestMapping("/system/patrolRoute")
public class PatrolRouteRecordController extends BaseController {
    @Autowired
    private IPatrolRouteRecordService patrolRouteRecordService;
    @Autowired
    private IRouteStationService iRouteStationService;

    /**
     * 查询巡线记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(PatrolRouteRecord patrolRouteRecord) {
        patrolRouteRecord.setDevid(Long.valueOf(41021));
        startPage();
        List<PatrolRouteRecord> list = patrolRouteRecordService.selectPatrolRouteRecordList(patrolRouteRecord);
        return getDataTable(list);
    }

    @GetMapping("/findTrail")
    public Result<Map> findTrail(String id) {

        Result<Map> result = new Result<>();
        Map<String, Object> datamap = new HashMap<>();

        PatrolRouteRecord record = patrolRouteRecordService.selectPatrolRouteRecordById(id);

        String devid = record.getDevid().toString();

        List<Map> list1 = new ArrayList(); //原轨迹
        List<Map> listAnhe = new ArrayList(); //安和轨迹

        List<Map> filteredList = new ArrayList(); //安和轨迹

        if (record.getTrail() != null && !record.getTrail().equals("")) {
            filteredList = JSON.parseArray(record.getTrail(), Map.class);


            for (Map<String, String> temp : filteredList) {
                list1.add(temp);
            }
            //按照时间排序
            Collections.sort(list1, new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    String tm1 = (String) o1.get("tm");
                    String tm2 = (String) o2.get("tm");
                    return tm1.compareTo(tm2);
                }
            });


            if (devid.equals("41006") || devid.equals("41021")) {
                int i = 5;
                int m = 5;

                for (int q = 20; i < list1.size(); i++) {
                    //取当经纬度 判断是否为0.0
                    String lt = list1.get(i).get("lt").toString();
                    String l0 = list1.get(i).get("ln").toString();

                    if (!lt.equals("0.0")) {

                        MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                        cordinatesVo.setLon(new BigDecimal(lt));
                        cordinatesVo.setLat(new BigDecimal(l0));
                        String o = list1.get(i).get("tm").toString();
                        String lo = list1.get(i).get("lo").toString();
                        cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                        Double nowLng = cordinatesVo.getLon().doubleValue(); //经度
                        Double nowLat = cordinatesVo.getLat().doubleValue(); //经度

                        Double lng = 0.0;
                        Double lat = 0.0;

                        //判断上一个 相差距离
                        if (i != m) {
                            if (i != m + 1) {
                                MapCordinatesVo cordinatesVo1 = new MapCordinatesVo();
                                cordinatesVo1.setLon(new BigDecimal(list1.get(i - 1).get("lt").toString()));
                                cordinatesVo1.setLat(new BigDecimal(list1.get(i - 1).get("ln").toString()));
                                cordinatesVo1 = CoordinatesConvertUtil.bd_encrypt(cordinatesVo1);

                                Double dlon = cordinatesVo1.getLon().doubleValue(); //经度
                                Double dlat = cordinatesVo1.getLat().doubleValue(); //经度

                                Double EARTH_RADIUS = 6378.137;
                                Double radLat1 = dlat * Math.PI / 180.0;
                                Double radLat2 = nowLat * Math.PI / 180.0;
                                Double a = radLat1 - radLat2;
                                Double b = (dlon * Math.PI / 180.0) - (nowLng * Math.PI / 180.0);
                                Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                                        + Math.cos(radLat1) * Math.cos(radLat2)
                                        * Math.pow(Math.sin(b / 2), 2)));
                                s = s * EARTH_RADIUS;
                                String sa = s.toString();
                                String str1;
                                int result1 = sa.indexOf("E");
                                if (result1 != -1) {
                                    str1 = s.toString().substring(0, s.toString().indexOf("E"));//截取@之前的字符串
                                } else {
                                    str1 = s.toString();
                                }

                                Double ss = Double.parseDouble(str1);
//                    System.out.println("^^^^"+ss+""+o);
                                //小于一百米 0.01十米 0.1一百米
                                if (ss < 2) {
//                            System.out.println("&&&&"+ss+""+o);
                                    lng = nowLng;
                                    lat = nowLat;
                                } else {
                                    list1.remove(i);
                                    i--;
                                }
                            } else {
                                lng = nowLng;
                                lat = nowLat;
                            }

                        } else {
                            lng = nowLng;
                            lat = nowLat;
                        }

                        if (lng != 0.0 && lat != 0.0) {
                            Map map = new HashMap<>();
                            map.put("lt", lng.toString());
                            map.put("ln", lat.toString());
                            if (o == null) {
                                map.put("tm", "");
                            } else {
                                map.put("tm", o);
                            }
                            map.put("lo", lo);
                            listAnhe.add(map);
                        }

                    } else {
                        list1.remove(i);
                        i--;
                    }
                }
            } else {
                for (Map map : list1) {
                    try {
                        MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                        cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                        cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                        cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                        map.put("lt", cordinatesVo.getLon());
                        map.put("ln", cordinatesVo.getLat());
                        Object o = map.get("tm");
                        if (o == null) {
                            map.put("tm", "");
                        }
                    } catch (Exception e) {
                        System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                    }
                }
            }
        }
        if (devid.equals("41006") || devid.equals("41021")) {
            datamap.put("trail", listAnhe);
        } else {
            datamap.put("trail", list1);
        }


        //====================================基准线路==========================
        //拼接路线
        List list = getLocalroute(record.getRouteId(), record.getDevid().toString());
        //整段
        datamap.put("localroute", list); //拼接
        result.setResult(datamap);
        return result;
    }

    //用于巡检时的动态轨迹展示
    @GetMapping("/findTrailNew")
    public Result<Map> findTrailNew(String id) {

        Result<Map> result = new Result<>();
        Map<String, Object> datamap = new HashMap<>();

        PatrolRouteRecord record = patrolRouteRecordService.selectPatrolRouteRecordById(id);

        String devid = record.getDevid().toString();

        List<Map> list1 = new ArrayList(); //原轨迹
        List<Map> listAnhe = new ArrayList(); //安和轨迹

        List<Map> filteredList = new ArrayList(); //安和轨迹

        if (record.getTrail() != null && !record.getTrail().equals("")) {
            filteredList = JSON.parseArray(record.getTrail(), Map.class);


            for (Map<String, String> temp : filteredList) {
                list1.add(temp);
            }
            //按照时间排序
            Collections.sort(list1, new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    String tm1 = (String) o1.get("tm");
                    String tm2 = (String) o2.get("tm");
                    return tm1.compareTo(tm2);
                }
            });


            if (devid.equals("41006") || devid.equals("41021")) {
                int i = 5;
                int m = 5;

                for (int q = 20; i < list1.size(); i++) {
                    //取当经纬度 判断是否为0.0
                    String lt = list1.get(i).get("lt").toString();
                    String l0 = list1.get(i).get("ln").toString();

                    if (!lt.equals("0.0")) {

                        MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                        cordinatesVo.setLon(new BigDecimal(lt));
                        cordinatesVo.setLat(new BigDecimal(l0));
                        String o = list1.get(i).get("tm").toString();
                        String lo = list1.get(i).get("lo").toString();
                        cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                        Double nowLng = cordinatesVo.getLon().doubleValue(); //经度
                        Double nowLat = cordinatesVo.getLat().doubleValue(); //经度

                        Double lng = 0.0;
                        Double lat = 0.0;

                        //判断上一个 相差距离
                        if (i != m) {
                            if (i != m + 1) {
                                MapCordinatesVo cordinatesVo1 = new MapCordinatesVo();
                                cordinatesVo1.setLon(new BigDecimal(list1.get(i - 1).get("lt").toString()));
                                cordinatesVo1.setLat(new BigDecimal(list1.get(i - 1).get("ln").toString()));
                                cordinatesVo1 = CoordinatesConvertUtil.bd_encrypt(cordinatesVo1);

                                Double dlon = cordinatesVo1.getLon().doubleValue(); //经度
                                Double dlat = cordinatesVo1.getLat().doubleValue(); //经度

                                Double EARTH_RADIUS = 6378.137;
                                Double radLat1 = dlat * Math.PI / 180.0;
                                Double radLat2 = nowLat * Math.PI / 180.0;
                                Double a = radLat1 - radLat2;
                                Double b = (dlon * Math.PI / 180.0) - (nowLng * Math.PI / 180.0);
                                Double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                                        + Math.cos(radLat1) * Math.cos(radLat2)
                                        * Math.pow(Math.sin(b / 2), 2)));
                                s = s * EARTH_RADIUS;
                                String sa = s.toString();
                                String str1;
                                int result1 = sa.indexOf("E");
                                if (result1 != -1) {
                                    str1 = s.toString().substring(0, s.toString().indexOf("E"));//截取@之前的字符串
                                } else {
                                    str1 = s.toString();
                                }

                                Double ss = Double.parseDouble(str1);
//                    System.out.println("^^^^"+ss+""+o);
                                //小于一百米 0.01十米 0.1一百米
                                if (ss < 2) {
//                            System.out.println("&&&&"+ss+""+o);
                                    lng = nowLng;
                                    lat = nowLat;
                                } else {
                                    list1.remove(i);
                                    i--;
                                }
                            } else {
                                lng = nowLng;
                                lat = nowLat;
                            }

                        } else {
                            lng = nowLng;
                            lat = nowLat;
                        }

                        if (lng != 0.0 && lat != 0.0) {
                            Map map = new HashMap<>();
                            map.put("lt", lng.toString());
                            map.put("ln", lat.toString());
                            if (o == null) {
                                map.put("tm", "");
                            } else {
                                map.put("tm", o);
                            }
                            map.put("lo", lo);
                            listAnhe.add(map);
                        }

                    } else {
                        list1.remove(i);
                        i--;
                    }
                }
            } else {
                for (Map map : list1) {
                    try {
                        MapCordinatesVo cordinatesVo = new MapCordinatesVo();
                        cordinatesVo.setLon(new BigDecimal(map.get("lt").toString()));
                        cordinatesVo.setLat(new BigDecimal(map.get("ln").toString()));
                        cordinatesVo = CoordinatesConvertUtil.bd_encrypt(cordinatesVo);
                        map.put("lt", cordinatesVo.getLon());
                        map.put("ln", cordinatesVo.getLat());
                        Object o = map.get("tm");
                        if (o == null) {
                            map.put("tm", "");
                        }
                    } catch (Exception e) {
                        System.out.println("转换坐标错误=" + JSON.toJSONString(map));
                    }
                }
            }
        }
        if (devid.equals("41006") || devid.equals("41021")) {
            datamap.put("trail", listAnhe);
        } else {
            datamap.put("trail", list1);
        }
        result.setResult(datamap);
        return result;
    }

    public List getLocalroute(String routeId, String devid) {
        List list = new ArrayList();
        Integer joint = 1;
        Map map = new HashMap();
        map.put("devid", devid);
        list.add(map);
        List l2 = new ArrayList();

        RouteStation routeStation = new RouteStation();
        routeStation.setRouteid(routeId);
        List<RouteStation> l = iRouteStationService.selectRouteStationList(routeStation);
        for (int i = 0; i < l.size(); i++) {
            Map m = new HashMap();
            RouteStation r = l.get(i);
            String longitude = r.getLongitude();
            String dimension = r.getDimension();
            m.put("lt", longitude);
            m.put("ln", dimension);
            l2.add(m);
            if (longitude.equals("0") && dimension.equals("0")) {
                joint = 2;
                List l3 = new ArrayList();
                for (int a = 0; a < l2.size() - 1; a++) {
                    l3.add(l2.get(a));
                }
                list.add(l3);
                l2.clear();
            }
        }


        return list;
    }

    /**
     * 导出巡线记录列表
     */
    @Log(title = "巡线记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PatrolRouteRecord patrolRouteRecord) {
        List<PatrolRouteRecord> list = patrolRouteRecordService.selectPatrolRouteRecordList(patrolRouteRecord);
        ExcelUtil<PatrolRouteRecord> util = new ExcelUtil<PatrolRouteRecord>(PatrolRouteRecord.class);
        util.exportExcel(response, list, "巡线记录数据");
    }

    /**
     * 获取巡线记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(patrolRouteRecordService.selectPatrolRouteRecordById(id));
    }

    /**
     * 新增巡线记录
     */
    @Log(title = "巡线记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PatrolRouteRecord patrolRouteRecord) {
        return toAjax(patrolRouteRecordService.insertPatrolRouteRecord(patrolRouteRecord));
    }

    /**
     * 修改巡线记录
     */
    @Log(title = "巡线记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PatrolRouteRecord patrolRouteRecord) {
        return toAjax(patrolRouteRecordService.updatePatrolRouteRecord(patrolRouteRecord));
    }

    /**
     * 删除巡线记录
     */
    @Log(title = "巡线记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(patrolRouteRecordService.deletePatrolRouteRecordByIds(ids));
    }
}
